package com.boot.web.serviceImpl;

import com.boot.frame.redis.JedisOperate;
import com.boot.web.dao.DepartmentDao;
import com.boot.web.dao.RoleDao;
import com.boot.web.dao.UserDao;
import com.boot.web.dao.UserRoleDao;
import com.boot.web.dto.LoginDTO;
import com.boot.web.dto.UserDTO;
import com.boot.web.entity.Department;
import com.boot.web.entity.Role;
import com.boot.web.entity.User;
import com.boot.web.entity.UserRole;
import com.boot.web.service.UserService;
import com.boot.web.vo.MenuPowerVO;
import com.boot.web.vo.UserVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.boot.constant.Constants;
import com.boot.exception.BusinessException;
import com.boot.web.enums.AllEnums;
import com.boot.base.serviceImpl.BaseServiceImpl;

import java.util.*;

/**
 * 系统用户信息业务层接口实现
 * @author 【zhouJie】
 * @date 2019-12-05 17:31:35
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private DepartmentDao departmentDao;

    @Override
    public User getUserByLoginName(String loginName) {
        return userDao.queryUserByLoginName(loginName);
    }

    @Override
    public UserVO login(LoginDTO loginDTO) {
        if (StringUtils.isNotBlank(loginDTO.getUsername()) && StringUtils.isNotBlank(loginDTO.getPassword()) && StringUtils.isNotBlank(loginDTO.getCaptchaId())) {
            User user = userDao.queryUserByLoginName(loginDTO.getUsername());
            if (user != null) {
                if (user.getStatus() == AllEnums.user_enable.getState()) {
                    if (StringUtils.equals(loginDTO.getPassword(), user.getPassword())) {
                        String strCode = JedisOperate.getObject(loginDTO.getCaptchaId()).toString();
                        if (StringUtils.equalsIgnoreCase(strCode, loginDTO.getImgCode())) {
                            return getUserInfo(user);
                        } else {
                            throw new BusinessException("验证码错误");
                        }
                    } else {
                        throw new BusinessException("账户或密码不正确");
                    }
                } else {
                    throw new BusinessException("账户已被禁用，请联系管理员");
                }
            } else {
                throw new BusinessException("账户不存在");
            }
        }
        return null;
    }

    @Override
    public UserVO getUserInfo(User user) {
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user, vo);
        List<UserRole> urList = userRoleDao.queryUserRoleByUserId(user.getId());
        if (urList.size() > 0) {
            Integer[] roleIds = new Integer[urList.size()];
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < urList.size(); i++) {
                Role r = roleDao.queryById(urList.get(i).getRoleId());
                roleIds[i] = r.getId();
                sb.append(r.getName() + " / ");
            }
            vo.setRoleIds(roleIds);
            vo.setRoleNames(sb.toString().substring(0, sb.toString().length() - 3));
        }
        Department department = departmentDao.queryById(user.getDepartmentId());
        if(department != null){
            vo.setDepartmentName(department.getTitle());
        }else{
            department = departmentDao.queryById(Constants.default_department);
            vo.setDepartmentName(department.getTitle());
            user.setDepartmentId(Constants.default_department);
            userDao.update(user);
        }
        return vo;
    }

    @Override
    public List<MenuPowerVO> getMenuPowerList(Integer userId) {
        List<MenuPowerVO> onePowerList = userDao.queryUserAllPowerByOneLevel(userId); // TODO 第一层
        int oneSize = onePowerList.size();
        List<MenuPowerVO> twoPowerList = userDao.queryUserAllPowerByTwoLevel(userId); // TODO 第二层
        int twoSize = onePowerList.size();
        List<MenuPowerVO> threePowerList = userDao.queryUserAllPowerByThreeLevel(userId); // TODO 第三层
        int threeSize = onePowerList.size();
        List<MenuPowerVO> menuList = new ArrayList<>();
        if (oneSize > 0) {
            List<MenuPowerVO> oneLevelList = new ArrayList<>();
            for (MenuPowerVO oneP : onePowerList) {
                if (oneP.getType() == 0 && oneP.getLevel() == 0 && oneP.getParentId() == null) {
                    if (twoSize > 0) {
                        List<MenuPowerVO> twoLevelList = new ArrayList<>();
                        for (MenuPowerVO twoP : twoPowerList) {
                            if (twoP.getType() == 0 && twoP.getLevel() == 1 && twoP.getParentId().equals(oneP.getId())) {
                                twoLevelList.add(twoP);
                                oneP.setChildren(twoLevelList);
                                if (threeSize > 0) {
                                    List<MenuPowerVO> threeLevelList = new ArrayList<>();
                                    for (MenuPowerVO threeP : threePowerList) {
                                        if (threeP.getType() == 0 && threeP.getLevel() == 2 && threeP.getParentId().equals(twoP.getId())) {
                                            threeLevelList.add(threeP);
                                            twoP.setChildren(threeLevelList);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    oneLevelList.add(oneP);
                }
            }
            menuList = oneLevelList;
        }
        return menuList;
    }

    @Override
    public boolean unLock(String afferent_password, String cache_password) {
        if(StringUtils.equals(afferent_password, cache_password)){
            return true;
        }else{
            throw new BusinessException("解锁密码不正确");
        }
    }

    @Override
    public List<UserVO> getUserVOPageList(Map<String, Object> map) {
        List<UserVO> userVOList = userDao.queryUserVOPageList(map);
        if (userVOList.size() > 0) {
            for (int i = 0; i < userVOList.size(); i++) {
                UserVO uvo = userVOList.get(i);
                List<UserRole> urList = userRoleDao.queryUserRoleByUserId(uvo.getId());
                if (urList.size() > 0) {
                    Integer[] roleIds = new Integer[urList.size()];
                    StringBuffer sb = new StringBuffer();
                    for (int j = 0; j < urList.size(); j++) {
                        UserRole ur = urList.get(j);
                        Role r = roleDao.queryById(ur.getRoleId());
                        roleIds[j] = r.getId();
                        sb.append(r.getName() + " / ");
                    }
                    uvo.setRoleIds(roleIds);
                    uvo.setRoleNames(sb.toString().substring(0, sb.toString().length() - 3));
                }
            }
        }
        return userVOList;
    }

    @Override
    public User updateUser(UserDTO userDTO) {
        User u = new User();
        User user = userDao.queryUserByLoginName(userDTO.getLoginName());
        if (user != null) {
            if (userDTO.getId() != user.getId()) {
                throw new BusinessException("登录账户已存在");
            } else {
                u.setLoginName(userDTO.getLoginName());
                User user1 = userDao.queryUserByPhone(userDTO.getPhone());
                if (user1 != null) {
                    if (userDTO.getId() != user1.getId()) {
                        throw new BusinessException("手机号码已存在");
                    } else {
                        u.setPhone(userDTO.getPhone());
//                        User user2 = userDao.queryUserByEmail(userDTO.getEmail());
//                        if (user2 != null) {
//                            if (userDTO.getId() != user2.getId()) {
//                                throw new BusinessException("邮箱已存在");
//                            } else {
//                                u.setEmail(userDTO.getEmail());
//                            }
//                        }

                    }
                }else{
                    u.setPhone(userDTO.getPhone());
                }
            }
        }else{
            u.setLoginName(userDTO.getLoginName());
        }
        u.setEmail(userDTO.getEmail()); // todo 可完善

        u.setStoreShopId(userDTO.getStoreShopId());
        u.setRealName(userDTO.getRealName());
        u.setPassword(userDTO.getPassword());
        u.setId(userDTO.getId());
        if (userDTO.getDepartmentId() != null) {
            u.setDepartmentId(userDTO.getDepartmentId());
        } else {
            u.setDepartmentId(Constants.default_department);
        }
        int row = userDao.update(u);
        if (row == 1) {
            List<UserRole> urList = userRoleDao.queryUserRoleByUserId(u.getId());
            if (urList.size() > 0) {
                for (int k = 0; k < urList.size(); k++) {
                    userRoleDao.delete(urList.get(k).getId());
                }
            }
            if (userDTO.getRoleIds().length > 0) {
                // String[] roleIds = userDTO.getRoleIds().split(",");
                for (int i = 0; i < userDTO.getRoleIds().length; i++) {
                    UserRole ur = new UserRole();
                    ur.setRoleId(userDTO.getRoleIds()[i]);
                    ur.setUserId(u.getId());
                    userRoleDao.save(ur);
                }
            } else {
                UserRole ur = new UserRole();
                ur.setRoleId(Constants.default_role);
                ur.setUserId(u.getId());
                userRoleDao.save(ur);
            }
        } else {
            throw new BusinessException("用户修改失败");
        }
        return u;
    }

    @Override
    public User saveUser(UserDTO userDTO) {
        User user = userDao.queryUserByLoginName(userDTO.getLoginName());
        if (user != null) {
            throw new BusinessException("登录账户已存在");
        } else {
            User user1 = userDao.queryUserByPhone(userDTO.getPhone());
            if (user1 != null) {
                throw new BusinessException("手机号码已存在");
            } else {
//                User user2 = userDao.queryUserByEmail(userDTO.getEmail());
//                if (user2 != null) {
//                    throw new BusinessException("邮箱已存在");
//                }
            }
        }
        User u = new User();
        u.setStatus(AllEnums.user_enable.getState());
        if (userDTO.getDepartmentId() != null) {
            u.setDepartmentId(userDTO.getDepartmentId());
        } else {
            u.setDepartmentId(Constants.default_department);
        }
        u.setUpdateTime(new Date());
        u.setEmail(userDTO.getEmail());
        u.setLoginName(userDTO.getLoginName());
        u.setRealName(userDTO.getRealName());
        u.setPassword(userDTO.getPassword());
        u.setPhone(userDTO.getPhone());
        u.setStoreShopId(userDTO.getStoreShopId());
        int row = userDao.save(u);
        if (row == 1) {
            if (userDTO.getRoleIds().length > 0) {
                // String[] roleIds = userDTO.getRoleIds().split(",");
                for (int i = 0; i < userDTO.getRoleIds().length; i++) {
                    UserRole ur = new UserRole();
                    ur.setRoleId(userDTO.getRoleIds()[i]);
                    ur.setUserId(u.getId());
                    userRoleDao.save(ur);
                }
            } else {
                UserRole ur = new UserRole();
                ur.setRoleId(Constants.default_role);
                ur.setUserId(u.getId());
                userRoleDao.save(ur);
            }
        } else {
            throw new BusinessException("用户添加失败");
        }
        return u;
    }

    @Override
    public boolean deleteUser(Integer userId) {
        List<UserRole> urList = userRoleDao.queryUserRoleByUserId(userId);
        if (urList.size() > 0) {
            for (int i = 0; i < urList.size(); i++) {
                userRoleDao.delete(urList.get(i).getId());
            }
            userDao.delete(userId);
            return true;
        }
        return false;
    }

    @Override
    public boolean batchDeleteUser(Integer[] ids) {
        if (ids.length > 0) {
            for (int i = 0; i < ids.length; i++) {
                List<UserRole> urList = userRoleDao.queryUserRoleByUserId(ids[i]);
                if (urList.size() > 0) {
                    for (int j = 0; j < urList.size(); j++) {
                        userRoleDao.delete(urList.get(j).getId());
                    }
                }
            }
            userDao.batchDelete(ids);
            return true;
        }
        return false;
    }

    @Override
    public boolean enableOrDisableUser(Integer userId) {
        User user = userDao.queryById(userId);
        if (user != null) {
            if (user.getStatus() == AllEnums.user_enable.getState()) {
                user.setStatus(AllEnums.user_disable.getState());
            } else if (user.getStatus() == AllEnums.user_disable.getState()) {
                user.setStatus(AllEnums.user_enable.getState());
            } else {
                //TODO 以后可以加其他的
            }
            userDao.update(user);
            return true;
        } else {
            throw new BusinessException("当前用户信息错误，无法操作");
        }
    }

    @Override
    public List<User> getUserByDepartmentId(Integer departmentId) {
        return userDao.queryUserByDepartmentId(departmentId);
    }

}
